package org.example.service;

import org.example.util.DBUtil;
import java.sql.*;
import java.util.*;

public class CartServiceImpl implements CartService {
    
    @Override
    public void addToCart(int userId, int productId, int quantity) {
        String sql = "INSERT INTO tb_cart (user_id, product_id, quantity) VALUES (?, ?, ?) " +
                    "ON DUPLICATE KEY UPDATE quantity = quantity + ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            pstmt.setInt(2, productId);
            pstmt.setInt(3, quantity);
            pstmt.setInt(4, quantity);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void removeFromCart(int userId, int productId) {
        String sql = "DELETE FROM tb_cart WHERE user_id = ? AND product_id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            pstmt.setInt(2, productId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void updateQuantity(int userId, int productId, int quantity) {
        String sql = "UPDATE tb_cart SET quantity = ? WHERE user_id = ? AND product_id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, quantity);
            pstmt.setInt(2, userId);
            pstmt.setInt(3, productId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public List<Map<String, Object>> getCartItems(int userId) {
        List<Map<String, Object>> cartItems = new ArrayList<>();
        String sql = "SELECT c.*, p.name, p.price, p.image FROM tb_cart c " +
                    "JOIN tb_product p ON c.product_id = p.product_id " +
                    "WHERE c.user_id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Map<String, Object> item = new HashMap<>();
                item.put("cartId", rs.getInt("cart_id"));
                item.put("productId", rs.getInt("product_id"));
                item.put("productName", rs.getString("name"));
                item.put("price", rs.getDouble("price"));
                item.put("quantity", rs.getInt("quantity"));
                item.put("image", rs.getString("image"));
                cartItems.add(item);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return cartItems;
    }
    
    @Override
    public String createOrder(int userId) {
        String orderNumber = generateOrderNumber();
        
        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);
            try {
                // 1. 创建订单
                String orderSql = "INSERT INTO tb_order (user_id, order_number, total_amount, order_status) " +
                                "VALUES (?, ?, 0, 'PENDING')";
                PreparedStatement orderStmt = conn.prepareStatement(orderSql, Statement.RETURN_GENERATED_KEYS);
                orderStmt.setInt(1, userId);
                orderStmt.setString(2, orderNumber);
                orderStmt.executeUpdate();
                
                ResultSet rs = orderStmt.getGeneratedKeys();
                int orderId = 0;
                if (rs.next()) {
                    orderId = rs.getInt(1);
                }
                
                // 2. 获取购物车商品
                double totalAmount = 0;
                List<Map<String, Object>> cartItems = getCartItems(userId);
                
                // 3. 创建订单明细
                String detailSql = "INSERT INTO tb_order_detail (order_id, product_id, quantity, unit_price) " +
                                 "VALUES (?, ?, ?, ?)";
                PreparedStatement detailStmt = conn.prepareStatement(detailSql);
                
                for (Map<String, Object> item : cartItems) {
                    detailStmt.setInt(1, orderId);
                    detailStmt.setInt(2, (Integer)item.get("productId"));
                    detailStmt.setInt(3, (Integer)item.get("quantity"));
                    detailStmt.setDouble(4, (Double)item.get("price"));
                    detailStmt.executeUpdate();
                    
                    totalAmount += (Double)item.get("price") * (Integer)item.get("quantity");
                }
                
                // 4. 更新订单总金额
                String updateOrderSql = "UPDATE tb_order SET total_amount = ? WHERE order_id = ?";
                PreparedStatement updateOrderStmt = conn.prepareStatement(updateOrderSql);
                updateOrderStmt.setDouble(1, totalAmount);
                updateOrderStmt.setInt(2, orderId);
                updateOrderStmt.executeUpdate();
                
                // 5. 清空购物车
                clearCart(userId);
                
                conn.commit();
                return orderNumber;
            } catch (SQLException e) {
                conn.rollback();
                throw e;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public void clearCart(int userId) {
        String sql = "DELETE FROM tb_cart WHERE user_id = ?";
        
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    private String generateOrderNumber() {
        return String.format("%tY%<tm%<td%<tH%<tM%<tS%04d",
                new java.util.Date(), (int)(Math.random() * 10000));
    }
} 